#!/bin/bash
# detail information format : V01.00.00.2554-24-geda375fb
version_detail=$(git describe)

#calculate number version information
version_info=$(echo ${version_detail##*V} | sed 's/-/ /g')
version_number=$(echo $version_info | awk '{printf "%s",$1}')
version_change=$(echo $version_info | awk '{printf "%d",$2}')
version_start=$(echo $version_number | sed 's/\./ /g' | awk '{printf "%d",$4}')
version_current=$(echo $(($version_start + $version_change)) | awk '{printf("%04d",$0)}')

version_01=$(echo $version_number | sed 's/\./ /g' | awk '{printf "%02d",$1}')
version_02=$(echo $version_number | sed 's/\./ /g' | awk '{printf "%02d",$2}')
version_03=$(echo $version_number | sed 's/\./ /g' | awk '{printf "%02d",$3}')
version_number=$version_01.$version_02.$version_03.$version_current

version_time=$(git log --pretty=format:'%ci' -n 1 | cut -c 1-19 | sed 's/-/\//g')

make_version_file() {
echo "#ifndef _VERSION_H"
echo "#define _VERSION_H"
echo ""
echo "#define AUTO_BUILD"
echo "#define LOCAL_VERSION_DETAIL "\"$version_detail\"
echo "#define LOCAL_VERSION_NUMBER "\"$version_number\"
echo "#define LOCAL_VERSION_TIME   "\"$version_time\"
echo ""
echo "const char * GetVersionTime() {"
echo "return LOCAL_VERSION_TIME;"
echo "}"
echo ""
echo "const char * GetVersionNumber() {"
echo "return LOCAL_VERSION_NUMBER;"
echo "}"
echo ""
echo "const char * GetVersionDetail() {"
echo "return LOCAL_VERSION_DETAIL;"
echo "}"
echo ""
echo "#endif"
}

for i in "$@"; do
  match_str=`echo ${i} | grep -- "^--output-file="`
  if [ -n "${match_str}" ]; then
    option="-file"
    file_name=${i##*=}
    break
  elif [ "${i}" == "-print" ]; then
    option="-print"
    break
  fi
done

case $option in
  "-print")
    make_version_file
    exit
    ;;

  "-file")
    mkdir $(dirname $file_name) >/dev/null 2>&1
    make_version_file >$file_name
    ;;

  *)
    ;;
esac

echo $version_number
